package com.meatball.authorization.config.handler

import com.meatball.authorization.config.JwtComponent
import com.meatball.authorization.repository.UserRepository
import com.meatball.core.config.AUTHORIZATION
import com.meatball.core.config.BEARER
import org.springframework.stereotype.Component
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes

@Component
class RoleHandler(
    private val userRepository: UserRepository,
    private val jwtComponent: JwtComponent
) {
    fun roles(): List<String> {
        // 使用安全调用和Elvis操作符来简化null检查和处理
        val token = (RequestContextHolder.getRequestAttributes() as? ServletRequestAttributes)
            ?.request
            ?.getHeader(AUTHORIZATION)
            ?.takeIf { it.startsWith(BEARER) }
            ?.substring(BEARER.length)
            ?.trim() ?: return emptyList()

        return userRepository.findByUsername(jwtComponent.extractUsername(token))
            ?.roles?.map { it.name } ?: emptyList()
    }
}